var localVideo = document.getElementById("localVideo");
var remoteVideo = document.getElementById("remoteVideo");

var localStream = null;
var remoteStream = null;
//进入房间
const SIGNAL_TYPE_JOIN = "join";
const SIGNAL_TYPE_RESP_JOIN = "resp-join"; //告之加入者对方是谁
const SIGNAL_TYPE_LEAVE = "leave";
const SIGNAL_TYPE_NEW_PEER = "new-peer";

const SIGNAL_TYPE_OFFER = "offer";
const SIGNAL_TYPE_ANSWER = "answer";
const SIGNAL_TYPE_CANDIDATE = "candidate";

var localUserId = Math.random().toString(36).substr(2);
var remoteUserId = -1;
var roomId = 0;

var pc = null;

function handleIceCandidate(event) {
    console.log("========handleIceCandidate=========");
    var candidate = event.candidate
    if (candidate) {
        var jsonMsg = {
            'cmd': 'candidate',
            'roomId': roomId,
            'uid': localUserId,
            'remoteUid': remoteUserId,
            'msg': candidate
        }

        zeroRTCEngine.sendMsg(jsonMsg)
    } else {
        console.log("end of candidate");
    }
}

function handleRemoteStreamAdd(event) {
    console.log("========handleRemoteStreamAdd=========");
    remoteStream = event.streams[0];
    remoteVideo.srcObject = remoteStream;


    if (event.candidate) {
        var jsonMsg = {
            'cmd': 'candidate',
            'roomId': roomId,
            'uid': localUserId,
            'remoteUid': remoteUserId,
            'msg': candidate
        }

        zeroRTCEngine.sendMsg(jsonMsg)
    } else {
        console.log("end of candidate");
    }
}


function createPeerConnection() {

    var defaultConfiguration = {
        bundlePolicy: "max-bundle",
        rtcpMuxPolicy: "require",
        iceTransportPolicy: "relay",//relay
        // 修改ice数组测试效果，需要进行封装
        iceServers: [
            {
                "urls": [
                    "turn:47.103.36.143:3478?transport=udp",
                    "turn:47.103.36.143:3478?transport=tcp" // 可以插入多个进行备选
                ],
                "username": "admin",
                "credential": "123456"
            },
            {
                "urls": [
                    "stun:47.103.36.143:3478"
                ]
            }
        ]
    };


    pc = new RTCPeerConnection(defaultConfiguration);
    pc.onicecandidate = handleIceCandidate;

    pc.ontrack = handleRemoteStreamAdd;

    localStream.getTracks().forEach(track => pc.addTrack(track, localStream))
}

// function createPeerConnection() {
//     pc = new RTCPeerConnection();
//     pc.onicecandidate = handleIceCandidate;

//     pc.ontrack = handleRemoteStreamAdd;

//     localStream.getTracks().forEach(track => pc.addTrack(track, localStream))
// }

function createOfferAndSendMsg(session) {
    pc.setLocalDescription(session).then(function () {
        var jsonMsg = {
            'cmd': 'offer',
            'roomId': roomId,
            'uid': localUserId,
            'remoteUid': remoteUserId,
            'msg': session
        }
        zeroRTCEngine.sendMsg(jsonMsg)
    }).catch(function () {
        console.log("=======createOfferAndSendMsg.setLocalDescription错误==========")
    });

}


function handleCreateOfferError() {
    console.log("=======handleCreateOfferError错误==========")
}

function createAnswerAndSendMsg(session) {
    pc.setLocalDescription(session).then(function () {
        var jsonMsg = {
            'cmd': 'answer',
            'roomId': roomId,
            'uid': localUserId,
            'remoteUid': remoteUserId,
            'msg': session
        }
        zeroRTCEngine.sendMsg(jsonMsg)
    }).catch(function () {
        console.log("=======createAnswerAndSendMsg.setLocalDescription错误==========")
    });

}


function handleCreateAnswerError() {
    console.log("=======handleCreateAnswerError==========")
}



var zeroRTCEngine;
var ZeroRTCEngine = function (wsUrl) {

    this.init(wsUrl)
    zeroRTCEngine = this;
    return this;
}

ZeroRTCEngine.prototype.init = function (wsUrl) {
    this.wsUrl = wsUrl;
    this.signaling = null;

}

ZeroRTCEngine.prototype.onOpen = function () {
    console.log('=======onOpen==========')
}

ZeroRTCEngine.prototype.onMessage = function (event) {

    console.log(event, '=======onMessage==========')


    var msg = JSON.parse(event.data);

    switch (msg.cmd) {
        case SIGNAL_TYPE_NEW_PEER:
            handleRemoteNewPeer(msg);
            break;

        case SIGNAL_TYPE_RESP_JOIN:
            handleRemoteRespJoin(msg);
            break;

        case SIGNAL_TYPE_LEAVE:
            handleRemotePeerLeave(msg);
            break;

        case SIGNAL_TYPE_OFFER:
            handleRemoteOffer(msg);
            break;

        case SIGNAL_TYPE_ANSWER:
            handleRemoteAnswer(msg);
            break;

        case SIGNAL_TYPE_CANDIDATE:
            handleRemoteCandidate(msg);
            break;
    }



}

ZeroRTCEngine.prototype.onError = function (ev) {
    console.log(ev, '=======onError==========')
}

ZeroRTCEngine.prototype.onClose = function (ev) {
    console.log(ev, '=======onClose==========')



}

ZeroRTCEngine.prototype.sendMsg = function (msg) {
    msg = JSON.stringify(msg);
    this.signaling.send(msg)
    console.log(msg, "===========sendMsg" + msg.cmd + "==============");
}

ZeroRTCEngine.prototype.createWebSocket = function () {

    var that = this;

    this.signaling = new WebSocket(this.wsUrl);

    this.signaling.onopen = function () {
        that.onOpen();
    }

    this.signaling.onmessage = function (ev) {
        that.onMessage(ev);
    }

    this.signaling.onerror = function (ev) {
        that.onError(ev);
    }

    this.signaling.onclose = function (ev) {
        that.onClose(ev);
    }

}


function doJoin() {
    var jsonMsg = {
        'cmd': 'join',
        'roomId': roomId,
        'uid': localUserId
    }

    zeroRTCEngine.sendMsg(jsonMsg)
}

function doLeave() {
    var jsonMsg = {
        'cmd': 'leave',
        'roomId': roomId,
        'uid': localUserId
    }
    zeroRTCEngine.sendMsg(jsonMsg)

    hungup();
}

function hungup() {
    localVideo.srcObject = null; // 关闭本地显示
    remoteVideo.srcObject = null;
    closeLocalStream();

    if (pc != null) {
        pc.close();
        pc = null;
    }
}

function closeLocalStream() {
    if (localStream != null) {
        localStream.getTracks().forEach(track => {
            track.stop();
        })
    }

}


function handleRemoteNewPeer(msg) {
    console.log(msg.remoteUid, "==============handleRemoteNewPeer============");
    remoteUserId = msg.remoteUid;

    doOffer()
}

function doOffer() {
    if (pc == null) {
        createPeerConnection()
    }

    pc.createOffer().then(createOfferAndSendMsg).catch(handleCreateOfferError);
}
function doAnswer() {

    pc.createAnswer().then(createAnswerAndSendMsg).catch(handleCreateAnswerError);
}


function handleRemoteRespJoin(msg) {
    console.log(msg.remoteUid, "==============handleRemoteNewPeer============");
    remoteUserId = msg.remoteUid;
}

function handleRemotePeerLeave(msg) {
    console.log(msg, "==============handleRemotePeerLeave============");
    remoteVideo.srcObject = null;

    if (pc != null) {
        pc.close();
        pc = null;
    }

}

function handleRemoteOffer(msg) {
    console.log(msg, "==============handleRemoteOffer============");

    if (pc == null) {
        createPeerConnection();
    }

    var desc = msg.msg;

    pc.setRemoteDescription(desc);

    doAnswer()

}

function handleRemoteAnswer(msg) {
    console.log(msg, "==============handleRemoteAnswer============");

    pc.setRemoteDescription(msg.msg)

}

function handleRemoteCandidate(msg) {
    console.log(msg, "==============handleRemoteCandidate============");
    var candidate = msg.msg;

    pc.addIceCandidate(candidate).catch(e => {
        console.log(e.name, "======addIceCandidate.catch=====")
    })
}


function openLocalStream(stream) {

    doJoin()

    localVideo.srcObject = stream;
    localStream = stream;
}

function InitLocalStream(type) {
    // getDisplayMedia
    // getUserMedia
    var map = {
        0: "getUserMedia",
        1: 'getDisplayMedia'
    }

    navigator.mediaDevices[map[type]]({
        audio: false,
        video: {
            width: clientWidth,
            height: clientHeight,
            facingMode: "user"
        }
    }).then(openLocalStream)
        .catch(function (e) {
            alert("getUserMedia() error: " + e.name)
        })
}

zeroRTCEngine = new ZeroRTCEngine('wss://www.besteasylearn.com/video_socket')
zeroRTCEngine.createWebSocket();


document.getElementById("joinBtn").onclick = function () {

    roomId = document.getElementById("roomId").value;

    if (roomId == 0 || roomId == "") {
        alert("请输入房间ID");
        return false;
    }
    console.log(roomId, "========roomId======");

    InitLocalStream(0);
}

document.getElementById("joinDesktopBtn").onclick = function () {

    roomId = document.getElementById("roomId").value;

    if (roomId == 0 || roomId == "") {
        alert("请输入房间ID");
        return false;
    }
    console.log(roomId, "========roomId======");

    InitLocalStream(1);
}



document.getElementById("leaveBtn").onclick = function () {
    console.log("========离开点击======");

    doLeave();
}

document.getElementById("exchagePosBtn").onclick = function () {
    console.log("========离开点击======");


    var oneCls = document.getElementById('localVideo').className;
    var twoCls = document.getElementById('remoteVideo').className;

    if (oneCls == "mainVideo") {
        document.getElementById('localVideo').className = "smallVideo";
        document.getElementById('remoteVideo').className = "mainVideo";
    } else {
        document.getElementById('localVideo').className = "mainVideo";
        document.getElementById('remoteVideo').className = "smallVideo";

    }
}